//***************************************************************
//  File:    SceneMIMEHandler.cpp
//  Date:    5/19/2009
//  Author:  wanglei (wanglei010407@163.com)
//-------------------------------------------------------------
//
//-------------------------------------------------------------
//  This file is part of Hare2D Game Engine.
//  Copyright (C) All Rights Reserved
//***************************************************************
//
//***************************************************************
#include "PCH.h"
#include "SceneMIMEHandler.h"

#include "ScenePage.h"
#include "GameObjectPage.h"

SceneMIMEHandler::SceneMIMEHandler()
{

}

bool SceneMIMEHandler::canHandle(const wxString& filename) const
{
    if (!filename.Lower().EndsWith(wxT(".scene")) && !filename.Lower().EndsWith(wxT(".gameobj")))
        return false;

    Object::Ptr obj = Object::importObject(filename.ToUTF8().data());
    if (!obj)
        return false;

    if (obj->getClassInfo()->isDerivedFrom(&SceneManager::CLASS_INFO))
        return true;

	if (obj->getClassInfo()->isDerivedFrom(&GameObject::CLASS_INFO))
		return true;

    return false;
}

bool SceneMIMEHandler::openFile(const wxString& filename)
{
    Object::Ptr obj = Object::importObject(filename.ToUTF8().data());

    if (!obj)
        return false;

    if (obj->getClassInfo()->isDerivedFrom(&SceneManager::CLASS_INFO)){
        return newPageScene((SceneManager*)obj.pointer(), false);
    }

	if (obj->getClassInfo()->isDerivedFrom(&GameObject::CLASS_INFO)){
		return newPageGameObject((GameObject*)obj.pointer(), false);
	}

    return false;
}

bool SceneMIMEHandler::newPageScene(SceneManager* scene, bool isModified)
{
    EditorPageManager* epm = Manager::getInstancePtr()->getEditorPageManager();

    epm->getNotebook()->Freeze();
    ScenePage* page = new ScenePage(epm->getNotebook(), this, scene);
    epm->addEditorPage(page);
    epm->getNotebook()->Thaw();

    if (isModified)
        page->setModified(isModified);

    int index = epm->getNotebook()->GetPageIndex(page);

    if (index != -1)
        epm->getNotebook()->SetSelection(index);

    return true;
}

bool SceneMIMEHandler::newPageGameObject(GameObject* obj, bool isModified)
{
	EditorPageManager* epm = Manager::getInstancePtr()->getEditorPageManager();

	epm->getNotebook()->Freeze();
	GameObjectPage* page = new GameObjectPage(epm->getNotebook(), this);
	epm->addEditorPage(page);
	epm->getNotebook()->Thaw();

	page->setGameObject(obj);

	if (isModified)
		page->setModified(isModified);

	int index = epm->getNotebook()->GetPageIndex(page);

	if (index != -1)
		epm->getNotebook()->SetSelection(index);

	return true;
}